# -*- coding: UTF-8 -*-
# __author__ = 'Sengo'
import math
import cv2
from settings import BASE_DIR
import numpy as np


def object_to_cylinder(Xc, Yc, Zc, W, Xo, Yo, Zo, H):
    """object map to cylinder, Xc,Yc, Zc分别是圆心，R为半径, Xo,Yo,Zo分别是Object上点的坐标"""
    try:
        R = W * 1.0 / (2*math.pi)
        distance = math.sqrt((Xo-Xc)*(Xo-Xc) + (Yo-Yc)*(Yo-Yc))  # 点和圆心的距离
        # 相似三角形，圆柱的中心等于物体的球心
        y = R * 1.0 * (Yo-Yc) / distance + Yo

        x = (R-Xc) * 1.0 * (Xo-Xc) / distance
        if Xo-Xc == 0:
            z = (Zo - Zc) * 1.0 * (y - Yc) / (Yo - Yc) + Zc
        else:
            z = (Zo-Zc) * 1.0 * (x-Xc) / (Xo-Xc) + Zc
        # 超出圆柱范围的
        if abs(z) > H*1.0/2:
            return 0, 0
        else:
            return x, z
    except Exception, e:
        print "object_to_cylinder:", e, (Xo-Xc), (Yo-Yc)


def cylinder_to_texture(x, z, H, W):
    """
    :param X: x,z is the point on Cylinder (object_to_cylinder)"
    :param H: is the high of the cylinder, h is the high of texture
    :param w: is the width of texture
    """""
    try:
        R = W * 1.0 / (2*math.pi)
        z = z + H * 1.0 / 2
        u = math.acos(x * 1.0 / R) / (2 * math.pi) * W
        v = z
        return u, v
    except Exception, e:
        print "cylinder_to_texture", e, x, R


def object_to_texture(Xc, Yc, Zc, Xo, Yo, Zo, W, H, img):
    try:
        x, z = object_to_cylinder(Zc, Xc, Yc, W, Xo, Yo, Zo, H)
        if x == 0 and z == 0:
            return 0, 0, 0
        u, v = cylinder_to_texture(x, z, H, W)
        color = img[int(v)][int(u)]
        return color
    except Exception, e:
        print "object_to_texture", e


def read_texture(file_name, W, H):
    try:
        file_name = BASE_DIR + '/data/texture/' + file_name
        img = cv2.imread(file_name)
        img = cv2.resize(img, (W, H), interpolation=cv2.INTER_CUBIC)
        # h, w = img.shape[:2]
        return img
    except Exception, e:
        print "read_texture", e


def find_uv_sphere(x, y, z, W, H):
    """
    :param x: x,y,z is the point on the object
    :param W,H: is the width, height of texture
    """
    try:
        Xc, Yc, Zc = 0, 0, 0
        c = np.mat([Xc, Yc, Zc])  # the centroid point of the Sphere
        p = np.mat([x, y, z])  # point on the object
        pc_vector = (c-p) / np.linalg.norm(c - p)
        pc = pc_vector.tolist()[0]
        X, Y, Z = pc[0], pc[1], pc[2]
        u = 0.5 + math.atan2(Z, X) / (2*math.pi)
        v = 0.5 - math.asin(Y) / math.pi
        Xtxture = int(u*W)
        Ytxture = int(v*H)
        return Xtxture, Ytxture
    except Exception, e:
        print "find_uv_sphere", e


if __name__ == '__main__':
    from data_service import read_data
    vs, l = read_data()
    for v in vs:
        print find_uv_sphere(0, 0, 0, v[0], v[1], v[2], 500, 500)
